package com.insurance.realms;
import com.insurance.common.ResultData;
import com.insurance.mapper.LoginRegisterMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;


/**
 * Created with IntelliJ IDEA.
 * User: zdk
 * Date: 2020/10/24 9:44
 * Description: 自定义的realm
 * Version: V1.0
 */
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired(required = false)
    private LoginRegisterMapper loginRegisterMapper;

    @Autowired
    private ResultData resultData;

    //授权：先认证通过，授权：张三你是销售总监角色，并且销售具备哪些(....)权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //得到认证通过后的员工姓名
        String user_phone = principalCollection.getPrimaryPrincipal().toString();
        //通过电话查询
        Set<String> authorMenuNames = loginRegisterMapper.getAuthorMenuByUser(user_phone);
        System.out.println("============授权==============");
        //授权对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //授权限菜单
        info.setStringPermissions(authorMenuNames);
        return info;
    }

    /**
     *
    认证：
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 页面传入的用户名称
        String user_phone= (String) authenticationToken.getPrincipal();
        // 根据员工名称获取密码
        String user_pwd = getPwdByEmployeeName(user_phone);
       if(user_pwd != null){
           SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user_phone,user_pwd,"myRealm");
           //加盐
           info.setCredentialsSalt(ByteSource.Util.bytes("zhuxiong"));
           System.out.println("========"+info.toString()+"=========");
           return info;
       }
        return null;
    }

    /**
     * 根据员工名称获取密码
     * @param user_phone
     * @return
     */
    private String getPwdByEmployeeName(String user_phone) {
       String user_pwd = loginRegisterMapper.queryPwdByUser_name(user_phone);
       if(user_pwd != null && !user_pwd.equals("")){
           return user_pwd;
       }
       return null;
    }


}
